(function(angular) {
	'use strict';
	angular.module('fs.waf').factory('trustedSrcService', trustedSrcService);
	trustedSrcService.$inject = [ '$q', 'loggerFactory', 'commonService', 'modalService','gridService','$filter','ajaxServiceFactory' ];
	function trustedSrcService($q, loggerFactory, commonService, modalService, gridService, $filter, ajaxServiceFactory) {
		var log = loggerFactory.getLogger("trustedSrcService");
		var ajaxService = ajaxServiceFactory.buildAjaxService({
			getServices : {
				url : 'do/cda/dataList/trustedSrcService',
				method : 'post'
			}
		});
		
		function getServiceOptions() {
			var defer = $q.defer();
			ajaxService.getServices().then(function(response) {
				defer.resolve(response);
			});
			return defer.promise;
		}
		function initDataOptions(ctrl) {
			ctrl.serviceCodeOptions = {};
			getServiceOptions().then(function(response) {
				angular.extend(ctrl.serviceCodeOptions, response);
			});
		}
		
		function updateSrcSite($scope, ctrl){
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.trustedSrcSites.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.trustedSrc.trustedSrcSites';
			ctrl.innerGridOptions.verifyData = 'vm.trustedSrcOld.trustedSrcSites';
			
			function rowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedRows = selectedRows;
			}
			
			ctrl.addTrustedSrcSite = function(row) {
				return $q(function(resolved, rejected){
				modalService.openCustomDialogs({
					'dialogsModule' : 'cda.site',
					'params':{ multiSelect : true, "filterSiteCodes" : ctrl.trustedSrc.trustedSrcSites},
					'btnCallback' : {
						'ok' : function(selectedRows) {
							if (!selectedRows || selectedRows.length == 0) {
								modalService.openErrorDialogs({
									messages : [ 'title.dialogs.info.norecsel' ]
								});
								return false;
							}
							if (!ctrl.trustedSrc.trustedSrcSites) {
								ctrl.trustedSrc.trustedSrcSites = [];
							} 
							if ( selectedRows.length > 0) {
								angular.forEach(selectedRows, function (srcSite, key) {
									srcSite.dataStatus = 'C';
									srcSite.siteCode = $filter('encode')(srcSite.siteCode);
									ctrl.trustedSrc.trustedSrcSites.push(srcSite);
									
								});
							}

						},
						'close' : function(){
							rejected();
						}
					}
				});
			  });
			};
		}
		
		return {
			initDataOptions : initDataOptions,
			updateSrcSite : updateSrcSite
			
		};
	}
})(angular);